package com.zero.demo.jms.web;

import net.sf.jasperreports.engine.*;
import org.assertj.core.util.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * @description: JRPDFServlet
 * @author: zero
 * @date: 2019/7/12
 */
@WebServlet(name = "JRPDFServlet", urlPatterns = "/JRPDFServlet")  //标记为servlet，以便启动器扫描。
public class JRPDFServlet extends HttpServlet {
    @Autowired
    DataSource dataSource;
    @Override
    public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        Connection connection = DataSourceUtils.getConnection(dataSource);
        try
        {
            //据据jasper文件生成JasperPrint对象
            ServletContext context = this.getServletConfig().getServletContext();
            String jrxmlPath = "F:\\WORKSPACE\\IWHALE\\beetlDemo\\src\\main\\resources\\templates\\";

            Map parameters = new HashMap(16);
            parameters.put("game_code","TTTTM000204000432");
            JasperCompileManager.compileReportToFile(jrxmlPath + "report2.jrxml", jrxmlPath + "report2.jasper");
            //JasperPrint jasperPrint = JasperFillManager.fillReport(jrxmlPath + "report2.jasper",parameters,connection);
            // (4)第4步导出成PDF指定格式
            //JasperExportManager.exportReportToPdfFile(jasperPrint,jrxmlPath +"report2.pdf");
            InputStream isRef = new FileInputStream(new File(jrxmlPath + "report2.jasper"));
            ServletOutputStream sosRef = response.getOutputStream();
            response.setContentType("application/pdf");
            JasperRunManager.runReportToPdfStream(isRef,sosRef,parameters, connection);
            sosRef.flush();
            sosRef.close();
        }
        catch (JRException e)
        {
            e.printStackTrace();
        }
    }

}
